package com.ls.lspicturebackend.manger.upload;

import cn.hutool.core.io.FileUtil;
import com.ls.lspicturebackend.exception.ErrorCode;
import com.ls.lspicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    public void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }

    @Override
    public void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "未上传图片");
        // 图片大小
        long pictureSize = multipartFile.getSize();
        final int ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(pictureSize / ONE_M > 5, ErrorCode.PARAMS_ERROR, "图片大于5M");
        // 文件后缀是否是图片后缀
        final List<String> ALLOW_PICTURE_SUFFIX = Arrays.asList("jpeg", "png", "jpg", "webp");
        String pictureSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!ALLOW_PICTURE_SUFFIX.contains(pictureSuffix), ErrorCode.PARAMS_ERROR, "文件格式不正确");
    }

    @Override
    public String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }
}
